package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.LinkedList;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.promotion.SalesPromotion;
import com.handu.luna.core.domain.search.SalesPromotionSearch;
import com.handu.luna.core.domain.user.UserRank;


@Controller
@RequestMapping("/promotion/salespromotion/*")
public class SalesPromotionController extends BaseController{
	
	@RequestMapping(value = "index",method = RequestMethod.GET)
	public BossModel index(String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {

		SalesPromotionSearch search = null;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (SalesPromotionSearch)JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), SalesPromotionSearch.class);
			
			return createModel("/promotion/salespromotion/index")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(SalesPromotion.selectCondition(search), pageable))
					.add("viewState", viewState);
		}else{
			search = new SalesPromotionSearch();
			return createModel("/promotion/salespromotion/index")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(pageable))
					.add("viewState", "");
		}
	}
	
	@RequestMapping(value = "index",method = RequestMethod.POST)
    public BossModel index(SalesPromotionSearch salesPromotionSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{

		return createModel()
				.add("salespromotionPage",context.getSalesPromotionRepository().findAll(SalesPromotion.selectCondition(salesPromotionSearch),pageable))
				.add("salesPromotionSearch", salesPromotionSearch)
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(salesPromotionSearch).toString().getBytes("UTF-8")));

	}
	
	
	
	@RequestMapping(value="add")
	public BossModel add(){
		SalesPromotion sp = new SalesPromotion();
		LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllNotSpecial());
		return createModel("promotion/salespromotion/info").add("sp",sp).add("userRanks", userRank);
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("promotion/salespromotion/info").add("sp", context.getSalesPromotionRepository().findOne(id))
				.add("userRanks", context.getUserRankRepository().findAllNotSpecial());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"salesPromotionName","beginTime","endTime","userRank","salesPromotionExplain"})
	public BossModel save(String viewState,@Valid @ModelAttribute("sp") final SalesPromotion sp,final BindingResult bindingResult, RedirectAttributes redirectAttributes, @PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{

		if(sp.getBeginTime() == null) {
			bindingResult.rejectValue("BeginTime", "misFormat", "请输入开始日期");
		}
		if(sp.getEndTime() == null) {
			bindingResult.rejectValue("EndTime", "misFormat", "请输入结束日期");
		}
		if(sp.getBeginTime() != null && sp.getEndTime() != null) {
			if(sp.getBeginTime().compareTo(sp.getEndTime()) != -1) {
				bindingResult.rejectValue("BeginTime", "misFormat", "开始时间必须小于结束时间");
			}
		}
		if(sp.getSalesPromotionName().trim().equals("")){
			bindingResult.rejectValue("SalesPromotionName", "", "请输入促销活动名称");
		}
		
		if (bindingResult.hasErrors()) {
			return createModel("promotion/salespromotion/info").add("userRanks", context.getUserRankRepository().findAllNotSpecial());			
		}
		
		String messagePrefix = sp.getSucessFlashMessage();
		if(sp.isNew()){
			context.getSalesPromotionRepository().save(sp);
		}else{
			sp.update();
		}
		
		SalesPromotionSearch search = null;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (SalesPromotionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), SalesPromotionSearch.class);
			return createModel("/promotion/salespromotion/index")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(SalesPromotion.selectCondition(search), pageable))
					.add("viewState", viewState)
					.add("message", messagePrefix);
		}else{
			search = new SalesPromotionSearch();
			return createModel("/promotion/salespromotion/index")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(pageable))
					.add("viewState", "")
					.add("message", messagePrefix);
		}
				
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{
		context.getSalesPromotionGoodsRepository().deleteByPromotionId((int)id);
		context.getSalesPromotionRepository().delete(id);
		
		SalesPromotionSearch search = null;
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			search = (SalesPromotionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), SalesPromotionSearch.class);
			return createModel("/promotion/salespromotion/salespromotion_table")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(SalesPromotion.selectCondition(search), pageable))
					.add("viewState", viewState);
		}else{
			search = new SalesPromotionSearch();
			return createModel("/promotion/salespromotion/salespromotion_table")
					.add("salesPromotionSearch", search)
					.add("salespromotionPage",context.getSalesPromotionRepository().findAll(pageable))
					.add("viewState", "");
		}

	}
}
